import React from 'react';
import { inject, observer } from 'mobx-react';
import { WeaCheckbox, WeaRightMenu, WeaDialog, WeaFormItem, WeaInput, WeaSearchGroup, WeaSelect, WeaDragula } from "ecCom";
import { Button, Tag, Input, Icon, message } from "antd";

/**
 * 考核设置-考核指标项-新增或编辑
 * jiansong 2019/6/18
 */
@inject("accessItemListStore")
@observer
export default class AccessItemOperation extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            inputVisible: false,
            inputValue: 10,
        };
        this.store = this.props.accessItemListStore;
    }

    render() {
        let { closeForm, showUpdataDialog, loading } = this.store;
        const menu = [
            {
                key: 'save',
                icon: <i className='icon-coms-search' />,
                content: '保存',
                onClick: () => this.operationData(),
            }, {
                key: 'close',
                icon: <i className='icon-coms-search' />,
                content: '关闭',
                onClick: () => {
                    this.store.formulaData = [];
                    closeForm();
                },
            }
        ]
        let buttons = [
            <Button loading={loading} type="primary" onClick={() => this.operationData()}>确定</Button>,
            <Button type="ghost" onClick={() => {
                this.store.formulaData = [];
                closeForm();
            }}>取消</Button>
        ];
        return (
            <WeaDialog
                style={{ width: 840, height: 500 }}
                buttons={buttons}
                hasScroll
                title={"考核指标项"}
                visible={showUpdataDialog}
                onCancel={() => {
                    this.store.formulaData = [];
                    closeForm();
                }}
            >
                <WeaRightMenu datas={menu}>
                    <div className="wea-workrelate-perform-itemoperation">
                        <WeaSearchGroup title="基础字段" items={this.getFormItem()} showGroup={true} col={1} />
                    </div>
                </WeaRightMenu>
            </WeaDialog>
        )
    }

    //操作数据
    operationData = () => {
        let { operation, formulaData, form: { itemname, formula, kpiformula, javaclass } } = this.store;
        if (itemname == "") {
            message.error("指标名称未填写")
            return;
        }
        if (formula == '12') {
            //校验数据
            let string = '', num = 0.11;
            formulaData.map((item, index) => {
                if (item.type == 'target_value' || item.type == 'completion_value') {
                    string += '(' + (num * (index + 1)) + ')';
                } else {
                    string += item.value;
                }
            });

            let flag = false
            try {
                var result = eval(string);
                if (isNaN(result) || 'Infinity'.indexOf(result) > -1) {
                    flag = true;
                }
            } catch (exception) {
                flag = true;
            }
            if (flag || kpiformula == '') {
                message.error("表达式不正确！请重新配置！")
                return;
            }
        } else if (formula == '13') {
            if (!javaclass || javaclass.indexOf('.') == -1) {
                message.error("请输入完整的java类名！")
                return;
            } else if (javaclass.substring(javaclass.lastIndexOf('.')) == '.java') {
                message.error("请不要包含.java后缀！")
                return;
            }
        }

        //提交数据
        operation();
        this.store.formulaData = []
    }

    //构建选择标签项
    buildTag() {
        let data = [
            { "type": "target_value", "value": "目标值" },
            { "type": "completion_value", "value": "完成值" },
            { "type": "left_parenthesis", "value": "(" },
            { "type": "right_parenthesis", "value": ")" },
            { "type": "addition", "value": "+" },
            { "type": "substruction", "value": "-" },
            { "type": "division", "value": "/" },
            { "type": "multiplication", "value": "*" },
        ];
        let dataList = [];
        data.forEach((item) => {
            dataList.push(
                <Tag color="#2db7f5" onClick={this.addTag.bind(this, item)}>
                    {item.value}
                </Tag>
            );
        });

        let { inputValue, inputVisible } = this.state
        dataList.push(
            inputVisible ?
                <Input
                    size="small"
                    type={"number"}
                    style={{ width: 78 }}
                    defaultValue={inputValue}
                    onChange={this.handleInputChange}
                    onBlur={this.handleInputConfirm}
                    onPressEnter={this.handleInputConfirm}
                /> :
                <Tag onClick={this.showInput} style={{ background: '#fff', borderStyle: 'dashed' }}>
                    <Icon type="plus" /> 数字
                </Tag>
        );
        return (
            <div style={{ "margin-bottom": "10px" }}>
                {dataList}
            </div>
        )
    }

    //标签删除操作
    handleTagClose = (removedTag) => {
        let { formulaData, onFormChange } = this.store;
        formulaData.splice(removedTag, 1);
        let showValue = "";
        formulaData.forEach((item) => {
            let name = item.value;
            showValue = showValue + name
        });
        onFormChange({ "kpiformula": showValue })
    };

    //往div中添加tag
    addTag(item) {
        let { formulaData, onFormChange } = this.store;
        item = { ...item, no: Math.random() }
        formulaData.push(item)
        let { accessItemListStore: { form: { kpiformula } } } = this.props;
        onFormChange({ "kpiformula": (kpiformula + item.value) })
    }

    //展示数字可输入框
    showInput = () => {
        this.setState({ inputVisible: true });
    };

    //获取最新排序的值
    onDrop = (datas) => {
        this.store.formulaData = datas;

        let showValue = "";
        datas.map((item) => {
            let name = item.value;
            showValue = showValue + name
        });
        this.store.onFormChange({ "kpiformula": showValue })
    };

    //数字输入框值改变
    handleInputChange = (e) => {
        this.setState({ inputValue: e.target.value });
    };

    //数字输入框值确定
    handleInputConfirm = () => {
        let { inputValue } = this.state
        this.addTag({ "type": "number", "value": inputValue })
        this.setState({
            inputVisible: false,
            inputValue: '10',
        });
    };

    getFormItem() {
        let { typeOption, formulaOption, form: { itemname, itemdesc, itemtype, itemunit, formula, javaclass, isvalid, kpiformula }, formulaData, onFormChange } = this.store;
        let items = [{
            com:
                <WeaFormItem label="指标名称" labelCol={{ span: 6 }} wrapperCol={{ span: 16 }}>
                    <WeaInput
                        value={itemname}
                        viewAttr={3}
                        onChange={(val) => onFormChange({ "itemname": val })}
                    />
                </WeaFormItem>
        }, {
            com:
                <WeaFormItem label="指标描述" labelCol={{ span: 6 }} wrapperCol={{ span: 16 }}>
                    <WeaInput
                        value={itemdesc}
                        onChange={(val) => onFormChange({ "itemdesc": val })}
                    />
                </WeaFormItem>
        }, {
            com:
                <WeaFormItem label="指标类型" labelCol={{ span: 6 }} wrapperCol={{ span: 16 }}>
                    <WeaSelect
                        options={typeOption}
                        value={itemtype}
                        onChange={(val) => onFormChange({ "itemtype": val })}
                    />
                </WeaFormItem>
        },];
        if (itemtype === "2") {
            items.push({
                com:
                    <WeaFormItem label="数值单位" labelCol={{ span: 6 }} wrapperCol={{ span: 16 }}>
                        <WeaInput
                            value={itemunit}
                            onChange={(val) => onFormChange({ "itemunit": val })}
                        />
                    </WeaFormItem>
            });
            items.push({
                com:
                    <WeaFormItem label="计算公式" labelCol={{ span: 6 }} wrapperCol={{ span: 16 }}>
                        <WeaSelect
                            options={formulaOption}
                            value={formula}
                            onChange={(val) => onFormChange({ "formula": val })}
                        />
                    </WeaFormItem>
            });
            if (formula === "12") {
                items.push({
                    com:
                        <WeaFormItem label="自定义公式" labelCol={{ span: 6 }} wrapperCol={{ span: 16 }}>
                            <div>
                                {this.buildTag()}
                                <WeaDragula
                                    container={() => this.refs["moving_dragula_div"]}
                                    canDrag={(clickDom) => jQuery(clickDom).hasClass("icon-coms-move")}
                                    datas={formulaData.slice()}
                                    getKeyFromData={record => record.no}
                                    getKeyFromDom={r => jQuery(r).attr("id")}
                                    onDrop={this.onDrop}
                                >
                                    <div ref="moving_dragula_div" style={{ border: "solid", "border-width": "thin", height: "100px" }}>
                                        {
                                            formulaData.map((item, index) => {
                                                return <Tag
                                                    id={item.no}
                                                    key={item.no}
                                                    className="icon-coms-move"
                                                    style={{ lineHeight: "22px !important" }}
                                                    closable={true}
                                                    onClose={() => this.handleTagClose(index)}>
                                                    {item.value}
                                                </Tag>
                                            })
                                        }
                                    </div>
                                    <div style={{ "margin-top": "10px" }}>
                                        {kpiformula ? "预览：" + kpiformula : ""}
                                    </div>
                                </WeaDragula>

                            </div>
                        </WeaFormItem>
                });
            }
            if (formula === "13") {
                items.push({
                    com:
                        <WeaFormItem label="java全类名" labelCol={{ span: 6 }} wrapperCol={{ span: 16 }}>
                            <div>
                                <WeaInput
                                    value={javaclass}
                                    onChange={(val) => onFormChange({ "javaclass": val })}
                                />
                                <div style={{ "margin-top": "5px", "color": "red" }}>
                                    说明：请输入完整类名（包含包名）且不要加.java后缀,如：com.xxxx.xxxx
                                    <br />此类必须实现接口：weaver.gp.execution.AccessItemManager
                                    <br />实现方法名为：public double getAccessItemScore(Map map)
                                    <br />参数含义：map中key值  user->User对象,cycle->考核周期,gval->目标值,cval->完成值
                                </div>
                            </div>
                        </WeaFormItem>
                });
            }
        }

        items.push({
            com:
                <WeaFormItem label="是否启用" labelCol={{ span: 6 }} wrapperCol={{ span: 16 }}>
                    <WeaCheckbox
                        display="switch"
                        value={isvalid}
                        onChange={(val) => onFormChange({ "isvalid": val })}
                    />
                </WeaFormItem>
        });
        return items
    }
}